import React, { useState } from "react";
import { InputItem, WhiteSpace, Button, Toast } from "antd-mobile";
import axios from "axios";

const AddressAdd = ({ history }) => {
    // 声明一个组件状态 (hooks)
    const [username, setUsername] = useState("");
    const [mobile, setMobile] = useState("");
    const [address, setAddress] = useState("");

    const onAddClicked = async () => {
        if (!username || !mobile || !address) {
            Toast.fail("缺少必填字段");
            return;
        }

        axios.defaults.headers.uid = JSON.parse(
            window.sessionStorage.getItem("user")
        ).id;

        const res = await axios.post("/addresses", {
            username,
            mobile,
            address,
            is_default: 1,
        });

        // 添加失败，提示用户
        if (res.data.code !== 201) {
            Toast.fail(res.data.message);
            return;
        }

        // 添加成功，跳转到地址管理页面
        history.push("/address/list");
    };

    return (
        <div className="address-list">
            <InputItem
                placeholder="收货人姓名"
                onChange={(v) => setUsername(v)}
            />

            <WhiteSpace />

            <InputItem
                placeholder="收货人手机号"
                onChange={(v) => setMobile(v)}
            />

            <WhiteSpace />

            <InputItem
                placeholder="收货人地址"
                onChange={(v) => setAddress(v)}
            />

            <WhiteSpace />

            <Button onClick={onAddClicked}>添加</Button>
        </div>
    );
};

export default AddressAdd;
